package com.company.matrix;

public class VisitAllPoints {
    public int minTimeToVisitAllPoints(int[][] points) {
        int totalTime = 0;
        for (int i = 0; i < points.length - 1; i++) {
            int[] a = points[i];
            int[] b = points[i + 1];
            int time = minTimeOfTwoPoints(a, b);

//            System.out.println("a(" + a[x] + "," + a[y] + ") " + "b(" + b[x] + "," + b[y] + ") time=" + time);
            totalTime += time;
        }
        return totalTime;
    }

    int x = 0;
    int y = 1;

    private int minTimeOfTwoPoints(int[] a, int[] b) {

        //判断两点相对位置
//        1、两点横坐标相同  走垂直路线最近
        if (a[x] == b[x]) {
            return Math.abs(a[y] - b[y]);
        }
//        纵坐标相同 走水平路线
        if (a[y] == b[y]) {
            return Math.abs(a[x] - b[x]);
        }
//        横纵坐标都不相同 判断是否在对角线上
        int s1 = Math.abs(b[x] - a[x]);
        int s2 = Math.abs(b[y] - a[y]);
        if (s1 == s2) {//在对角线上 走对角线
            return s1;
        }

        //如果没办法直接计算  先移动一步 横向或者纵向 递归检查
        //计算绝对距离  S1 S2 那个方向能最快的移动到 以上三个条件中
        int[] na = new int[2];
        //对角线移动一次

        int stepY = b[y] - a[y] > 0 ? 1 : -1;
        na[y] = a[y] + stepY;

        int stepX = b[x] - a[x] > 0 ? 1 : -1;
        na[x] = a[x] + stepX;

        return 1 + minTimeOfTwoPoints(na, b);
    }


}
